#define F_CPU 1000000UL
#include <avr/sfr_defs.h>
#include <avr/io.h>
#include <util/delay.h>
#include <avr/sleep.h>
#include <inttypes.h>
#include <util/atomic.h>
#include <avr/interrupt.h> 
#define LED_BITE_SELECT PORTC    //当前选择的显示的7位数码管
#define LED_BITE_DATA PORTD       //当前数码管的数据

//#pragma interrupt_handler timer0_ovf_isr:iv_TIM0_OVF

int g_Time_Count;
//建立数组，存储各个数字对应的数码管显示段位对应的二进制
int LED_TEXT[24] = {0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE0,
                        0xFE, 0xF6, 0xEE, 0x3E, 0x9C, 0x7A, 0x9E, 0x8E,
                        0xCE, 0x1C, 0x6E, 0x7C, 0x0A, 0x10, 0x02, 0x00};


void Port_Init()
{
    DDRD = 0xFF;
    DDRC = 0xFF;
    PORTD = 0x00;
    PORTC = 0xFF;
}

void Device_Init()
{
    Port_Init();


 //stop errant interrupts until set up
 cli(); //disable all interrupts
 timer0_init();

 MCUCR = 0x00;
 //GICR  = 0x00;
 TIMSK = 0x01; //timer interrupt sources
 sei(); //re-enable interrupts
 //all peripherals are now initialized

}

void timer0_init()
{    
    TCCR0 = 0x00; //stop
    TCNT0 = 0x83; //set count
    TCCR0 = 0x03; //start timer
}


void Show_Led(int wNum)    //将数字显示在数码管上
{
    int chBit;
    for(chBit = 0x08; chBit > 0; chBit >>= 1)
    {
        LED_BITE_DATA = ~LED_TEXT[wNum % 10];
        LED_BITE_SELECT = chBit;
        wNum /= 10;
        if(wNum == 0)
        {
            return;
        }
    }
}

void Count_Increase(void)    //将统计次数增加
{
    g_Time_Count++;
    if(g_Time_Count > 9999)
    {
        g_Time_Count = 0;
    }
}

//void timer0_ovf_isr(void)    //中断程序，在达到1s时将统计次数加一
ISR(TIM0_OVF_vect)   //中断程序，在达到1s时将统计次数加一
{
    static int wCount = 0;
    TCNT0 = 0x83; //reload counter value
    if(wCount >= 1000) 
    {
        wCount = 0;
        Count_Increase();
    }
    wCount++;
}

void main()
{
    g_Time_Count = 0;
    Device_Init();
    while(1)
    {
        Show_Led(g_Time_Count);
    }
}

